package com.arlen.centre.filter;

import com.arlen.until.thread.WxMessageUuidThread;
import com.arlen.until.xml.RequestToMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author Arlen
 * @Description 将用发送信息存入redis 对比直接存入线程将会快很多
 * @Date 9:56 下午 2021/4/22
 **/
@Component
@Order(1)
@WebFilter("/*")
public class GetInformationFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;//不要范型，不要范型！


    private static final ThreadLocal<String> t_uuid = new ThreadLocal<>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        HttpServletRequest servletRequest = (HttpServletRequest) request;


        t_uuid.set(UUID.randomUUID().toString());
        String method = servletRequest.getMethod();
        if (method.equals("POST") && ((HttpServletRequest) request).getRequestURL().toString().contains("cutIn")) {
            if (redisTemplate.opsForValue().setIfAbsent(t_uuid.get(), "", 1000, TimeUnit.SECONDS)) {
                try {
                    String uuid = UUID.randomUUID().toString();
                    WxMessageUuidThread.set(uuid);
                    // Map<String, Object> mesMap = RequestToMap.parseXml(servletRequest);

                    Map<String, Object> stringObjectMap = RequestToMap.parseXml2(servletRequest); //解析简单的xml

                    //  String s = RequestToMap.inputStream2String(request.getInputStream(), "utf-8");

                    redisTemplate.opsForValue().setIfAbsent(uuid, stringObjectMap, 1000, TimeUnit.SECONDS);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        chain.doFilter(request, response);
                    } catch (IOException | ServletException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                redisTemplate.delete(t_uuid.get());
                try {
                    chain.doFilter(request, response);
                } catch (IOException | ServletException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                chain.doFilter(request, response);
            } catch (IOException | ServletException e) {
                e.printStackTrace();
            }
        }
    }

}